from django.shortcuts import render, redirect, HttpResponse
from web.forms import project
from django.http import JsonResponse
from web import models
from utils.tencent.cos import create_bucket
from utils.Md5 import uid
import time


def project_list(request):
    dic = {
        'status': 1,
        'msg': ''
    }
    # 获取项目进行展示
    if request.method == 'GET':
        project_lists = {
            'my': [],
            'star': [],
            'join': []
        }
        # 我创建的项目的
        my_create_project = models.Project.objects.filter(creator=request.tracer.user)
        for item in my_create_project:
            if item.star:
                project_lists['star'].append({'value': item, 'type': 'my'})
            else:
                project_lists['my'].append({'value': item, 'type': 'my'})
        # 我参加的项目
        my_join_project = models.ProjectUser.objects.filter(user=request.tracer.user)
        for join in my_join_project:
            if join.star:
                project_lists['star'].append({'value': join.project, 'type': 'join'})
            else:
                project_lists['join'].append({'value': join.project, 'type': 'join'})
        form = project.add_project(request)
        return render(request, 'project_list.html', locals())
    form = project.add_project(request, data=request.POST)
    if form.is_valid():
        # 手动赋值
        Bucket = '{}-{}-1305448189'.format(request.tracer.user.telephone, str(int(time.time())))
        region = 'ap-chengdu'
        form.instance.creator = request.tracer.user
        form.instance.bucket = Bucket
        form.instance.region = region
        # 保存数据
        # 创建bucket
        create_bucket(Bucket=Bucket)
        form.save()
        return JsonResponse(dic)
    dic['status'] = 0
    dic['msg'] = form.errors
    return JsonResponse(dic)


def add_star(request, project_type, project_id):
    '''添加星标'''
    if project_type == 'my':
        models.Project.objects.filter(creator=request.tracer.user, pk=project_id, star=False).update(star=True)

    elif project_type == 'join':
        models.Project.objects.filter(creator=request.tracer.user, pk=project_id, star=False).update(star=True)
    else:
        redirect('project')
    return redirect('project')


def un_star(request, project_type, project_id):
    '''添加星标'''
    if project_type == 'my':
        models.Project.objects.filter(creator=request.tracer.user, pk=project_id, star=True).update(star=False)

    elif project_type == 'join':
        models.Project.objects.filter(creator=request.tracer.user, pk=project_id, star=True).update(star=False)
    else:
        redirect('project')
    return redirect('project')
